<template>
  <div class="costume-container">
    <!-- 分类管理部分 -->
    <el-card
      v-loading="loading"
      class="category-card"
      element-loading-text="正在加载分类数据..."
    >
      <div class="card-header">
        <div class="left">
          <span class="title">汉服分类管理</span>
          <el-tag type="info" effect="plain" size="small">
            共 {{ categories.length }} 个分类
          </el-tag>
        </div>
        <div class="actions">
          <el-button type="primary" @click="handleAddCategory">
            <el-icon><Plus /></el-icon>新增分类
          </el-button>
          <el-button type="success" @click="handleAIUpload">
            <el-icon><Upload /></el-icon>AI上传
          </el-button>
        </div>
      </div>

      <!-- 分类列表 -->
      <div class="category-list">
        <el-collapse v-model="activeCategories" @change="handleCategoryExpand">
          <el-collapse-item
            v-for="category in categories"
            :key="category.id"
            :name="category.id"
          >
            <template #title>
              <div class="category-header">
                <div class="category-info">
                  <el-image
                    v-if="category.coverImage"
                    :src="category.coverImage"
                    class="category-cover"
                    fit="cover"
                    style="
                      width: 40px;
                      height: 40px;
                      border-radius: 4px;
                      margin-right: 10px;
                    "
                    @click.stop="handlePreviewImage(category.coverImage)"
                  >
                    <template #error>
                      <div class="image-slot">
                        <el-icon><Picture /></el-icon>
                      </div>
                    </template>
                  </el-image>
                  <span class="name">{{ category.name }}</span>
                  <el-tag size="small" effect="plain" type="success">
                    {{ category.children?.length || 0 }} 个子分类
                  </el-tag>

                  <el-tag
                    v-if="category.showInBanner"
                    size="small"
                    effect="plain"
                    type="warning"
                  >
                    <el-icon><Picture /></el-icon>
                    轮播展示
                  </el-tag>
                  <el-tag
                    v-if="category.isRecommend"
                    size="small"
                    effect="plain"
                    type="danger"
                  >
                    <el-icon><Star /></el-icon>
                    推荐分类
                  </el-tag>
                </div>
                <div class="actions">
                  <el-button-group>
                    <el-button
                      link
                      type="primary"
                      @click.stop="handleAddSubCategory(category)"
                    >
                      <el-icon><Plus /></el-icon>添加子分类
                    </el-button>
                    <el-button
                      link
                      type="primary"
                      @click.stop="handleEditCategory(category)"
                    >
                      <el-icon><Edit /></el-icon>编辑
                    </el-button>
                    <el-button
                      link
                      type="danger"
                      @click.stop="handleDeleteCategory(category)"
                    >
                      <el-icon><Delete /></el-icon>删除
                    </el-button>
                  </el-button-group>
                </div>
              </div>
            </template>

            <div class="sub-categories">
              <el-table
                :data="category.children"
                border
                stripe
                :header-cell-style="{ background: '#f5f7fa' }"
                :row-class-name="getRowClassName"
              >
                <el-table-column prop="name" label="子分类名称" min-width="180">
                  <template #default="{ row }">
                    <div class="name-cell">
                      <!-- 二级分类 -->
                      <template v-if="row.isSecondLevel">
                        <div class="second-level-header">
                          <el-tag type="primary" effect="plain" size="small"
                            >二级分类</el-tag
                          >
                          <span class="sub-category-name second-level">{{
                            row.name
                          }}</span>
                          <el-tag
                            v-if="row.childCount > 0"
                            size="small"
                            effect="plain"
                            type="success"
                          >
                            {{ row.childCount }} 个子分类
                          </el-tag>
                        </div>
                      </template>

                      <!-- 三级分类 -->
                      <template v-else-if="row.isThirdLevel">
                        <span class="parent-name">{{ row.parentName }} / </span>
                        <span class="sub-category-name">{{ row.name }}</span>
                      </template>

                      <!-- 其他情况 -->
                      <template v-else>
                        <span class="sub-category-name">{{ row.name }}</span>
                      </template>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="sort"
                  label="排序"
                  width="80"
                  align="center"
                />
                <el-table-column
                  prop="favoriteCount"
                  label="收藏数"
                  width="100"
                  align="center"
                >
                  <template #default="{ row }">
                    <el-tag type="warning" effect="plain" class="favorite-tag">
                      <el-icon><Star /></el-icon>
                      {{ row.favoriteCount || 0 }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column label="封面图" width="120">
                  <template #default="{ row }">
                    <el-image
                      v-if="row.coverImage"
                      :src="row.coverImage"
                      class="cover-thumbnail"
                      fit="cover"
                      @click.stop="handlePreviewImage(row.coverImage)"
                    >
                      <template #error>
                        <div class="image-slot">
                          <el-icon><Picture /></el-icon>
                        </div>
                      </template>
                    </el-image>
                    <div v-else class="no-cover">
                      <el-icon><Picture /></el-icon>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column label="预览图" min-width="320">
                  <template #default="{ row }">
                    <div class="preview-images">
                      <el-scrollbar>
                        <div class="images-wrapper">
                          <el-image
                            v-for="(image, index) in row.previewImages?.slice(
                              0,
                              3
                            )"
                            :key="index"
                            :src="image"
                            fit="contain"
                            class="preview-image"
                            @click.stop="
                              handlePreviewImage(image, row.previewImages)
                            "
                          >
                            <template #error>
                              <div class="image-slot">
                                <el-icon><Picture /></el-icon>
                              </div>
                            </template>
                          </el-image>
                        </div>
                      </el-scrollbar>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="180" fixed="right">
                  <template #default="{ row }">
                    <el-button-group>
                      <!-- 二级分类且有子分类时显示查看子分类按钮 -->
                      <el-button
                        v-if="row.isSecondLevel && row.childCount > 0"
                        link
                        type="primary"
                        @click="handleViewSubCategories(row)"
                      >
                        <el-icon><View /></el-icon>查看子分类
                      </el-button>

                      <!-- 二级分类显示添加子分类按钮 -->
                      <el-button
                        v-if="row.isSecondLevel"
                        link
                        type="primary"
                        @click="handleAddThirdCategory(row)"
                      >
                        <el-icon><Plus /></el-icon>添加子分类
                      </el-button>

                      <!-- 所有分类都显示编辑和删除按钮 -->
                      <el-button
                        link
                        type="primary"
                        @click="handleEditSubCategory(row)"
                      >
                        <el-icon><Edit /></el-icon>编辑
                      </el-button>
                      <el-button
                        link
                        type="danger"
                        @click="handleDeleteSubCategory(row)"
                      >
                        <el-icon><Delete /></el-icon>删除
                      </el-button>
                    </el-button-group>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-collapse-item>
        </el-collapse>
      </div>
    </el-card>

    <!-- 分类编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      v-loading="loading"
      :title="getDialogTitle"
      width="500px"
      destroy-on-close
      element-loading-text="正在处理，请稍候..."
      @close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="categoryForm"
        :rules="rules"
        label-width="100px"
        @submit.prevent
      >
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="categoryForm.name" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="categoryForm.sort" :min="0" :max="999" />
        </el-form-item>
        <el-form-item v-if="!isSubCategory" label="展示轮播">
          <el-switch
            v-model="categoryForm.showInBanner"
            @change="handleBannerToggle"
          />
          <div class="form-tip">开启后将在首页轮播图中展示</div>
        </el-form-item>
        <el-form-item v-if="!isSubCategory" label="推荐分类">
          <el-switch
            v-model="categoryForm.isRecommend"
            :active-value="1"
            :inactive-value="0"
            @change="handleRecommendToggle"
          />
          <div class="form-tip">开启后将在首页推荐分类中展示</div>
        </el-form-item>
        <el-form-item label="封面图">
          <div class="cover-upload">
            <el-image
              v-if="categoryForm.coverImage"
              :src="categoryForm.coverImage"
              class="cover-preview"
              fit="cover"
            >
              <template #error>
                <div class="image-slot">
                  <el-icon><Picture /></el-icon>
                </div>
              </template>
            </el-image>
            <el-upload
              v-else
              class="upload-cover"
              :auto-upload="false"
              :show-file-list="false"
              :on-change="handleCoverUploadSuccess"
              :before-upload="handleBeforeUpload"
              accept="image/*"
            >
              <div class="upload-placeholder">
                <el-icon><Plus /></el-icon>
                <span>设置封面</span>
              </div>
            </el-upload>
          </div>
          <div class="form-tip">设置分类的主要展示图片</div>
        </el-form-item>
        <el-form-item v-if="isSubCategory" label="预览图" prop="previewImages">
          <div class="preview-images">
            <el-image
              v-for="(image, index) in categoryForm.previewImages"
              :key="index"
              :src="image"
              fit="contain"
              class="preview-image"
            >
              <template #error>
                <div class="image-slot">
                  <el-icon><Picture /></el-icon>
                </div>
              </template>
            </el-image>
            <el-upload
              v-if="categoryForm.previewImages.length < 9"
              class="upload-preview"
              :action="uploadUrl"
              :show-file-list="false"
              :on-success="handleUploadSuccess"
              :before-upload="handleBeforeUpload"
              accept="image/*"
              multiple
            >
              <el-icon><Plus /></el-icon>
            </el-upload>
          </div>
          <div class="upload-tip">
            <span
              >最多上传9张图片，当前已上传
              {{ categoryForm.previewImages.length }}/9</span
            >
            <span v-if="categoryForm.previewImages.length >= 9" class="warning">
              已达上限，保存后可继续上传
            </span>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button :disabled="loading" @click="dialogVisible = false"
          >取消</el-button
        >
        <el-button
          type="primary"
          :loading="loading"
          :disabled="loading"
          @click="submitForm"
          >{{ loading ? "提交中..." : "确定" }}</el-button
        >
      </template>
    </el-dialog>

    <!-- 图片预览 -->
    <el-image-viewer
      v-if="previewVisible"
      :url-list="previewImages"
      :initial-index="previewIndex"
      @close="previewVisible = false"
    />

    <!-- 三级分类对话框 -->
    <el-dialog
      v-model="subCategoryDialogVisible"
      :title="`${currentSubCategory?.name || ''} 的子分类`"
      width="80%"
      destroy-on-close
      class="sub-category-dialog"
    >
      <div class="dialog-header">
        <div class="info">
          <el-tag type="primary" effect="dark">二级分类</el-tag>
          <span class="category-name">{{ currentSubCategory?.name }}</span>
          <el-tag type="info" effect="plain">
            共 {{ currentSubCategory?.children?.length || 0 }} 个子分类
          </el-tag>
        </div>
        <el-button
          type="primary"
          size="small"
          @click="handleAddThirdCategory(currentSubCategory)"
        >
          <el-icon><Plus /></el-icon>添加子分类
        </el-button>
      </div>

      <el-table
        :data="currentSubCategory?.children || []"
        border
        stripe
        :header-cell-style="{ background: '#f5f7fa' }"
      >
        <el-table-column prop="name" label="子分类名称" min-width="180">
          <template #default="{ row }">
            <div class="name-cell">
              <span class="parent-category">{{ row.parentName }} / </span>
              <span class="sub-category-name">{{ row.name }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="sort" label="排序" width="80" align="center" />
        <el-table-column
          prop="favoriteCount"
          label="收藏数"
          width="100"
          align="center"
        >
          <template #default="{ row }">
            <el-tag type="warning" effect="plain" class="favorite-tag">
              <el-icon><Star /></el-icon>
              {{ row.favoriteCount || 0 }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="封面图" width="120">
          <template #default="{ row }">
            <el-image
              v-if="row.coverImage"
              :src="row.coverImage"
              class="cover-thumbnail"
              fit="cover"
              @click="handlePreviewImage(row.coverImage)"
            >
              <template #error>
                <div class="image-slot">
                  <el-icon><Picture /></el-icon>
                </div>
              </template>
            </el-image>
            <div v-else class="no-cover">
              <el-icon><Picture /></el-icon>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="预览图" min-width="320">
          <template #default="{ row }">
            <div class="preview-images">
              <el-scrollbar>
                <div class="images-wrapper">
                  <el-image
                    v-for="(image, index) in row.previewImages?.slice(0, 3)"
                    :key="index"
                    :src="image"
                    fit="contain"
                    class="preview-image"
                    @click="handlePreviewImage(image, row.previewImages)"
                  >
                    <template #error>
                      <div class="image-slot">
                        <el-icon><Picture /></el-icon>
                      </div>
                    </template>
                  </el-image>
                </div>
              </el-scrollbar>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button-group>
              <el-button
                link
                type="primary"
                @click="handleViewSubCategories(row)"
              >
                <el-icon><View /></el-icon>查看子分类
              </el-button>
              <el-button
                link
                type="primary"
                @click="handleEditSubCategory(row)"
              >
                <el-icon><Edit /></el-icon>编辑
              </el-button>
              <el-button
                link
                type="danger"
                @click="handleDeleteSubCategory(row)"
              >
                <el-icon><Delete /></el-icon>删除
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- AI上传对话框 -->
    <el-dialog
      v-model="aiUploadDialogVisible"
      v-loading="aiUploadLoading"
      title="AI智能识别"
      width="800px"
      destroy-on-close
      :close-on-click-modal="false"
      element-loading-text="正在进行AI识别..."
      class="ai-upload-dialog"
      :style="{ height: '640px', overflow: 'hidden' }"
      @close="handleAIUploadClose"
    >
      <div class="ai-upload-container">
        <div class="preview-area">
          <div class="preview-card">
            <el-upload
              :auto-upload="false"
              :show-file-list="false"
              :on-change="handleAIUploadChange"
              accept="image/*"
              class="ai-upload"
            >
              <div v-if="!aiUploadImageUrl" class="upload-placeholder">
                <el-icon><Plus /></el-icon>
                <span>选择汉服图片</span>
                <div class="upload-tip">支持jpg、png、jpeg格式</div>
              </div>
              <template v-else>
                <img :src="aiUploadImageUrl" class="preview-image" />
                <div class="image-overlay">
                  <el-icon><Edit /></el-icon>
                  <span>更换图片</span>
                </div>
              </template>
            </el-upload>
            <div
              v-if="!aiPredictions.length && aiUploadImageUrl"
              class="action-row"
            >
              <el-button
                type="primary"
                :disabled="aiUploadLoading"
                class="analyze-btn"
                @click="submitAIUpload"
              >
                <el-icon><View /></el-icon>开始识别
              </el-button>
            </div>
          </div>
        </div>

        <div v-if="aiPredictions.length > 0" class="prediction-area">
          <div class="prediction-header">
            <div class="header-icon">
              <el-icon><Star /></el-icon>
            </div>
            <h3>AI识别结果</h3>
          </div>

          <el-radio-group v-model="aiSelectedCategory" class="prediction-list">
            <div
              v-for="(prediction, index) in aiPredictions"
              :key="index"
              class="prediction-item"
              :class="{
                'is-selected': prediction.class === aiSelectedCategory,
                'high-confidence': prediction.probability > 90
              }"
            >
              <el-radio :label="prediction.class">
                <div class="prediction-content">
                  <div class="prediction-info">
                    <span class="prediction-name">{{ prediction.class }}</span>
                    <span
                      class="prediction-percent"
                      :class="{ 'high-percent': prediction.probability > 90 }"
                      >{{ prediction.probability.toFixed(2) }}%</span
                    >
                  </div>
                  <div class="prediction-bar">
                    <div
                      class="prediction-progress"
                      :style="{
                        width: `${prediction.probability.toFixed(2)}%`,
                        background:
                          prediction.probability > 90
                            ? 'linear-gradient(90deg, #67c23a, #409eff)'
                            : 'linear-gradient(90deg, #409eff, #67c23a)'
                      }"
                    />
                  </div>
                </div>
              </el-radio>
            </div>

            <!-- 添加手动输入选项 -->
            <div
              class="prediction-item manual-item"
              :class="{
                'is-selected': aiSelectedCategory === 'manual'
              }"
            >
              <el-radio label="manual">
                <div class="prediction-content">
                  <div class="prediction-info">
                    <span class="prediction-name">
                      <el-icon class="manual-icon"><Edit /></el-icon>
                      识别错误/纠正
                    </span>
                  </div>
                </div>
              </el-radio>
            </div>
          </el-radio-group>

          <!-- 手动输入表单 -->
          <div v-if="aiSelectedCategory === 'manual'" class="manual-input-area">
            <el-input
              v-model="manualCategoryName"
              placeholder="请输入正确的分类名称"
              clearable
            >
              <template #prefix>
                <el-icon><Edit /></el-icon>
              </template>
            </el-input>
          </div>

          <div class="action-row">
            <el-button
              type="success"
              :disabled="!isValidCategorySelection"
              class="add-category-btn"
              @click="addAICategory"
            >
              <el-icon><Plus /></el-icon>添加为分类
            </el-button>
          </div>
        </div>
      </div>
      <template #footer>
        <el-button
          :disabled="aiUploadLoading"
          @click="aiUploadDialogVisible = false"
          >取消</el-button
        >
        <el-button
          v-if="!aiPredictions.length && aiUploadImageUrl"
          type="primary"
          :loading="aiUploadLoading"
          :disabled="!aiUploadFile || aiUploadLoading"
          @click="submitAIUpload"
          >开始识别</el-button
        >
        <el-button
          v-else-if="aiPredictions.length"
          type="success"
          :disabled="!isValidCategorySelection"
          @click="addAICategory"
          >添加为分类</el-button
        >
      </template>
    </el-dialog>

    <!-- 分类选择对话框 -->
    <el-dialog
      v-model="categorySelectionDialogVisible"
      v-loading="loadingSubCategories"
      title="选择分类"
      width="800px"
      destroy-on-close
      class="category-selection-dialog"
      @close="handleAIUploadClose"
    >
      <div class="dialog-content">
        <el-form
          :model="selectedCategoryForm"
          :rules="rules"
          label-width="100px"
          @submit.prevent
        >
          <el-form-item label="父分类" prop="parentId">
            <el-select
              v-model="selectedParentCategory"
              placeholder="请选择父分类"
              @change="handleParentCategoryChange"
            >
              <el-option
                v-for="category in categories"
                :key="category.id"
                :label="category.name"
                :value="category.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="二级分类" prop="secondId">
            <el-select
              v-model="selectedSecondCategory"
              placeholder="请选择二级分类"
              @change="handleSecondCategoryChange"
            >
              <el-option
                v-for="category in subCategoriesForSelection"
                :key="category.id"
                :label="category.name"
                :value="category.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="三级分类" prop="thirdId">
            <el-select
              v-model="selectedThirdCategory"
              placeholder="请选择三级分类"
              :loading="loadingThirdCategories"
              @change="handleThirdCategoryChange"
            >
              <el-option
                v-for="category in thirdCategoriesForSelection"
                :key="category.id"
                :label="category.name"
                :value="category.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="标签名称" prop="name">
            <el-input v-model="selectedTagName" placeholder="请输入标签名称" />
          </el-form-item>
          <el-form-item label="图片" prop="imageUrl">
            <el-input v-model="selectedImageUrl" placeholder="请输入图片URL" />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button
          :disabled="loadingSubCategories"
          @click="submitCategorySelection"
          >提交</el-button
        >
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, watch } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import type {
  FormInstance,
  TableInstance,
  UploadFile,
  UploadFiles
} from "element-plus";
import { formatDateTime } from "@/utils/date";
import { formatImageUrl } from "@/utils/tools";

import {
  Plus,
  Edit,
  Delete,
  Picture,
  Upload,
  Download,
  Star,
  View
} from "@element-plus/icons-vue";
import {
  getCostumeCategory,
  updateCostumeCategory,
  addCategory,
  addCostume,
  deleteCategory,
  getSubCategories
} from "@/api/costumes";

// 状态定义
const loading = ref(false);
const searchFormRef = ref<FormInstance>();
const formRef = ref<FormInstance>();
const tableRef = ref<TableInstance>();
const selectedIds = ref<number[]>([]);
const dialogVisible = ref(false);
const dialogType = ref<"add" | "edit">("add");
const previewVisible = ref(false);
const previewImages = ref<string[]>([]);
const previewIndex = ref(0);
const categories = ref<any[]>([]);
const isSubCategory = ref(false);
const currentCategory = ref<any | null>(null);
const parentCategory = ref<any | null>(null);
const activeCategories = ref<string[]>([]);
const uploadUrl = ref("https://api.example.com/upload");
const subCategoryDialogVisible = ref(false);
const currentSubCategory = ref<any>(null);

// AI上传相关状态
const aiUploadDialogVisible = ref(false);
const aiUploadFile = ref<File | null>(null);
const aiUploadImageUrl = ref("");
const aiUploadLoading = ref(false);
const aiPredictions = ref<any[]>([]);
const aiSelectedCategory = ref("");
const manualCategoryName = ref("");

// 添加一个计算属性来检查分类选择是否有效
const isValidCategorySelection = computed(() => {
  if (aiSelectedCategory.value === "manual") {
    return manualCategoryName.value.trim().length >= 2;
  }
  return !!aiSelectedCategory.value;
});

// AI上传处理函数
const handleAIUpload = () => {
  aiUploadDialogVisible.value = true;
  aiUploadFile.value = null;
  aiUploadImageUrl.value = "";
  aiPredictions.value = [];
  aiSelectedCategory.value = "";
  manualCategoryName.value = "";
};

// 处理AI上传文件改变
const handleAIUploadChange = (file: any) => {
  aiUploadFile.value = file.raw;
  if (file.raw) {
    // 使用URL.createObjectURL而不是FileReader转base64
    aiUploadImageUrl.value = URL.createObjectURL(file.raw);
  }
  return false;
};

// 提交AI识别
const submitAIUpload = async () => {
  if (!aiUploadFile.value) {
    ElMessage.warning("请先选择图片");
    return;
  }

  aiUploadLoading.value = true;
  try {
    const formData = new FormData();
    formData.append("file", aiUploadFile.value);

    // 使用代理URL避免跨域问题
    const response = await fetch("/ai-api/predict", {
      method: "POST",
      body: formData
    });

    if (!response.ok) {
      throw new Error(`请求失败: ${response.status}`);
    }

    const result = await response.json();
    console.log("AI识别结果:", result);

    // 处理返回结果，适配不同的格式
    if (Array.isArray(result) && result.length > 0) {
      // 处理返回的数组格式
      const item = result[0];
      if (item.code === 200 && item.data && Array.isArray(item.data)) {
        aiPredictions.value = item.data;
        aiSelectedCategory.value = item.data[0]?.class || "";
        ElMessage.success("AI识别成功");
        return;
      }
    } else if (result.success && Array.isArray(result.predictions)) {
      // 处理之前的格式
      aiPredictions.value = result.predictions;
      aiSelectedCategory.value = result.predictions[0]?.class || "";
      ElMessage.success("AI识别成功");
      return;
    }

    // 如果不符合预期格式，报错
    ElMessage.error("AI识别结果格式不正确");
    console.error("AI识别结果格式不正确:", result);
  } catch (error) {
    console.error("AI识别出错:", error);
    ElMessage.error("AI识别请求出错");
  } finally {
    aiUploadLoading.value = false;
  }
};

// 修改addAICategory方法，添加分类选择对话框而不是直接创建新分类
const addAICategory = () => {
  if (!isValidCategorySelection.value) {
    if (
      aiSelectedCategory.value === "manual" &&
      !manualCategoryName.value.trim()
    ) {
      ElMessage.warning("请输入分类名称");
    } else {
      ElMessage.warning("请选择一个分类");
    }
    return;
  }

  // 显示分类选择对话框
  categorySelectionDialogVisible.value = true;
  // 设置将要添加的标签名称
  if (aiSelectedCategory.value === "manual") {
    selectedTagName.value = "#" + manualCategoryName.value.trim();
  } else {
    selectedTagName.value = "#" + aiSelectedCategory.value;
  }

  // 图片URL保存下来
  selectedImageUrl.value = aiUploadImageUrl.value;

  // 默认选择第一个分类，如果有的话
  if (categories.value.length > 0) {
    selectedParentCategory.value = categories.value[0].id;
    // 加载二级分类
    loadSubCategoriesForSelection(selectedParentCategory.value);
  }
};

// 添加新的状态变量
const selectedThirdCategory = ref(""); // 选择的三级分类ID
const thirdCategoriesForSelection = ref<any[]>([]);
const loadingThirdCategories = ref(false);

// 添加处理三级分类变化的方法
const handleThirdCategoryChange = (categoryId: string) => {
  console.log("选择三级分类:", categoryId);
  selectedThirdCategory.value = categoryId;

  // 找到对应的三级分类对象
  const selectedCategory = thirdCategoriesForSelection.value.find(
    c => c.id === categoryId
  );
  console.log("选中的三级分类对象:", selectedCategory);

  // 打印更多信息，帮助调试
  console.log("所有三级分类:", thirdCategoriesForSelection.value);
  console.log("当前选中的三级分类ID:", selectedThirdCategory.value);
};

// 加载三级分类的方法
const loadThirdCategoriesForSelection = async (categoryId: string) => {
  if (!categoryId) return;

  loadingThirdCategories.value = true;
  try {
    const response = await getSubCategories(categoryId);
    console.log("获取三级分类响应:", response);

    if (response?.data && Array.isArray(response.data)) {
      // 处理和映射三级分类
      thirdCategoriesForSelection.value = response.data.map(item => ({
        id: item.id,
        name: item.name,
        parentId: categoryId,
        rawData: item // 保存原始数据以便调试
      }));

      console.log("处理后的三级分类:", thirdCategoriesForSelection.value);

      // 默认选择第一个三级分类，如果有的话
      if (thirdCategoriesForSelection.value.length > 0) {
        selectedThirdCategory.value = thirdCategoriesForSelection.value[0].id;
        console.log("默认选择的三级分类ID:", selectedThirdCategory.value);
      } else {
        selectedThirdCategory.value = "";
        console.log("没有找到三级分类");
      }
    } else {
      thirdCategoriesForSelection.value = [];
      selectedThirdCategory.value = "";
      console.log("没有找到三级分类");
    }
  } catch (error) {
    console.error("加载三级分类失败:", error);
    ElMessage.error("加载三级分类失败");
    thirdCategoriesForSelection.value = [];
  } finally {
    loadingThirdCategories.value = false;
  }
};

// 添加新的状态变量
const categorySelectionDialogVisible = ref(false);
const selectedParentCategory = ref(""); // 选择的一级分类ID
const selectedSecondCategory = ref(""); // 选择的二级分类ID
const selectedTagName = ref(""); // 选中的标签名称
const selectedImageUrl = ref(""); // 选中的图片URL
const subCategoriesForSelection = ref<any[]>([]);
const loadingSubCategories = ref(false);

// 修改加载二级分类的方法，确保正确的ID映射
const loadSubCategoriesForSelection = async (categoryId: string) => {
  if (!categoryId) return;

  loadingSubCategories.value = true;
  try {
    const response = await getSubCategories(categoryId);
    console.log("获取二级分类响应:", response);

    if (response?.data && Array.isArray(response.data)) {
      // 只获取二级分类，确保ID正确，并保存完整的原始数据（包括children）
      subCategoriesForSelection.value = response.data.map(item => ({
        id: item.id,
        name: item.name,
        parentId: categoryId,
        rawData: item // 保存完整的原始数据，包括children字段
      }));

      console.log("处理后的二级分类:", subCategoriesForSelection.value);

      // 默认选择第一个二级分类，如果有的话
      if (subCategoriesForSelection.value.length > 0) {
        selectedSecondCategory.value = subCategoriesForSelection.value[0].id;
        console.log("默认选择的二级分类ID:", selectedSecondCategory.value);

        // 选择第一个二级分类后，自动加载该分类的子分类
        handleSecondCategoryChange(selectedSecondCategory.value);
      } else {
        selectedSecondCategory.value = "";
      }
    } else {
      subCategoriesForSelection.value = [];
      selectedSecondCategory.value = "";
      console.log("没有找到二级分类");
    }
  } catch (error) {
    console.error("加载二级分类失败:", error);
    ElMessage.error("加载二级分类失败");
    subCategoriesForSelection.value = [];
  } finally {
    loadingSubCategories.value = false;
  }
};

// 处理一级分类变化
const handleParentCategoryChange = (categoryId: string) => {
  console.log("选择一级分类:", categoryId);
  selectedParentCategory.value = categoryId;
  // 清空二级分类选择
  selectedSecondCategory.value = "";
  // 重新加载二级分类
  loadSubCategoriesForSelection(categoryId);
};

// 处理二级分类变化
const handleSecondCategoryChange = (categoryId: string) => {
  console.log("选择二级分类:", categoryId);
  selectedSecondCategory.value = categoryId;
  selectedThirdCategory.value = ""; // 清空三级分类选择

  // 找到对应的二级分类对象
  const selectedCategory = subCategoriesForSelection.value.find(
    c => c.id === categoryId
  );
  console.log("选中的二级分类对象:", selectedCategory);

  // 直接从二级分类的children中获取三级分类，而不是再次请求API
  if (
    selectedCategory &&
    selectedCategory.rawData &&
    Array.isArray(selectedCategory.rawData.children)
  ) {
    thirdCategoriesForSelection.value = selectedCategory.rawData.children.map(
      child => ({
        id: child.id,
        name: child.name,
        parentId: categoryId,
        rawData: child
      })
    );

    console.log(
      "从二级分类children中获取的三级分类:",
      thirdCategoriesForSelection.value
    );

    // 默认选择第一个三级分类，如果有的话
    if (thirdCategoriesForSelection.value.length > 0) {
      selectedThirdCategory.value = thirdCategoriesForSelection.value[0].id;
      console.log("默认选择的三级分类ID:", selectedThirdCategory.value);
    } else {
      selectedThirdCategory.value = "";
      console.log("没有找到三级分类");
    }
  } else {
    thirdCategoriesForSelection.value = [];
    selectedThirdCategory.value = "";
    console.log("二级分类没有children属性或者children不是数组");
  }
};

// 提交分类选择，将标签添加到选定的分类下
const submitCategorySelection = async () => {
  console.log("提交时的一级分类ID:", selectedParentCategory.value);
  console.log("提交时的二级分类ID:", selectedSecondCategory.value);
  console.log("提交时的三级分类ID:", selectedThirdCategory.value);
  console.log("提交时的标签名称:", selectedTagName.value);

  // 根据实际需求调整验证逻辑
  if (!selectedParentCategory.value || !selectedSecondCategory.value) {
    ElMessage.warning("请选择父分类和二级分类");
    return;
  }

  if (!selectedTagName.value) {
    ElMessage.warning("标签名称不能为空");
    return;
  }

  try {
    loading.value = true;

    // 添加CSS动画样式到头部
    const styleId = "eco-animation-styles";
    if (!document.getElementById(styleId)) {
      const styleEl = document.createElement("style");
      styleEl.id = styleId;
      styleEl.textContent = `
        @keyframes spin {
          0% { transform: rotate(0deg); }
          100% { transform: rotate(360deg); }
        }

        @keyframes progressAnim {
          0% { width: 0%; }
          80% { width: 80%; }
          100% { width: 100%; }
        }

        .eco-compression-dialog .el-message-box__header {
          background-color: #67c23a;
          color: white;
        }

        .eco-compression-dialog .el-message-box__title {
          color: white;
        }

        .eco-progress-animation {
          animation: progressAnim 3s ease-in-out forwards;
        }
      `;
      document.head.appendChild(styleEl);
    }

    // 创建一个Promise，在压缩完成后resolve
    const compressionPromise = new Promise(resolve => {
      let messageBoxInstance = null;

      // 显示环保信息动画 - 使用纯CSS动画
      ElMessageBox.alert(
        '<div style="text-align:center;padding:20px;">' +
          '<div style="margin-bottom:20px;">' +
          '<i class="el-icon-refresh" style="font-size:40px;color:#67c23a;display:inline-block;animation:spin 2s linear infinite;"></i>' +
          '<div style="margin-top:15px;background:#eee;border-radius:20px;height:15px;position:relative;overflow:hidden;">' +
          '<div class="eco-progress-animation" style="background:linear-gradient(90deg,#67c23a,#409eff);height:100%;border-radius:20px;width:0%"></div>' +
          '<div id="compression-status" style="position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);color:#606266;font-size:12px;">正在压缩中...</div>' +
          "</div></div>" +
          '<div style="text-align:left;border-top:1px dashed #dcdfe6;padding-top:15px;">' +
          '<div style="font-size:16px;font-weight:bold;color:#67c23a;margin-bottom:10px;"><i class="el-icon-leaf" style="margin-right:8px;"></i>节能环保，绿色上传</div>' +
          '<div style="font-size:15px;margin-bottom:8px;">10000 次访问服务器端减少的二氧化碳排放量约为 1270g</div>' +
          '<div style="font-size:12px;color:#909399;margin-bottom:15px;">计算方式: (50×1024 - 400)÷400×0.01×10000 = 1270g</div>' +
          '<div style="background:#f0f9eb;padding:10px;border-radius:5px;font-size:14px;">' +
          "<span>相当于:</span>" +
          '<div style="margin-top:5px;display:flex;align-items:center;"><i class="el-icon-tree" style="color:#67c23a;margin-right:8px;"></i><span>一棵树一天吸收的二氧化碳量</span></div>' +
          '<div style="margin-top:5px;display:flex;align-items:center;"><i class="el-icon-lightning" style="color:#67c23a;margin-right:8px;"></i><span>节约了约4.88度电</span></div>' +
          "</div></div></div>",
        "环保信息",
        {
          dangerouslyUseHTMLString: true,
          confirmButtonText: "确定",
          customClass: "eco-compression-dialog",
          showClose: false,
          closeOnClickModal: false,
          closeOnPressEscape: false,
          beforeClose: (action, instance, done) => {
            // 正常情况下不会触发，因为会自动关闭
            done();
          },
          callback: (action, instance) => {
            messageBoxInstance = instance;
          }
        }
      );

      // 在动画快结束时更新状态文本
      setTimeout(() => {
        const statusElement = document.getElementById("compression-status");
        if (statusElement) {
          statusElement.textContent = "压缩完成!";
        }
      }, 2500);

      // 动画结束后自动关闭弹窗并继续执行
      setTimeout(() => {
        // 关闭messageBox
        if (messageBoxInstance && messageBoxInstance.close) {
          messageBoxInstance.close();
        } else {
          // 如果无法获取实例，尝试使用DOM方式关闭
          const closeBtn = document.querySelector(
            ".eco-compression-dialog .el-button"
          );
          if (closeBtn && closeBtn instanceof HTMLElement) {
            closeBtn.click();
          }
        }
        // 延迟一小段时间确保弹窗关闭动画完成
        setTimeout(resolve, 300);
      }, 3000);
    });

    // 等待压缩完成
    await compressionPromise;

    // 构建请求数据
    const formData = new FormData();
    if (aiUploadFile.value) {
      formData.append("files", aiUploadFile.value);
    }

    console.log("选择的父分类ID:", selectedParentCategory.value);
    console.log("选择的二级分类ID:", selectedSecondCategory.value);
    console.log("选择的三级分类ID:", selectedThirdCategory.value);

    // 确定要使用的parentId：优先使用三级分类ID，如果没有则使用二级分类ID
    const costumesId = selectedThirdCategory.value;

    // 提交带有parentId的请求
    await addCostume(formData, {
      id: costumesId
    });

    ElMessage.success("添加成功");

    // 关闭所有对话框
    categorySelectionDialogVisible.value = false;
    aiUploadDialogVisible.value = false;

    // 重新加载数据
    loadData();

    // 清理状态
    resetAIUploadState();
  } catch (error) {
    console.error("添加标签失败:", error);
    ElMessage.error("添加标签失败");
  } finally {
    loading.value = false;
  }
};

// 修改重置状态方法
const resetAIUploadState = () => {
  aiUploadFile.value = null;
  aiUploadImageUrl.value = "";
  aiPredictions.value = [];
  aiSelectedCategory.value = "";
  manualCategoryName.value = "";
  selectedParentCategory.value = "";
  selectedSecondCategory.value = "";
  selectedThirdCategory.value = "";
  selectedTagName.value = "";
  selectedImageUrl.value = "";
  thirdCategoriesForSelection.value = [];
};

// 修改handleAIUploadClose方法
const handleAIUploadClose = () => {
  resetAIUploadState();
};

// 分类数据接口定义
interface SubCategoryItem {
  id: string;
  name: string;
  parentId: string;
  description?: string;
  categoryId: string;
  url?: string;
  icon?: string;
  sortOrder: number;
  salesVolume: number;
  createdTime: string;
  updatedTime: string;
  updatedBy?: string;
  status: number;
  price: number;
  stock: number;
}

interface CategoryWithChildren {
  id?: string;
  pid?: string;
  name: string;
  url?: string;
  isRecommend?: number;
  isBanner?: number;
  descs?: string | null;
  content?: string | null;
  icon?: string;
  parentId?: string;
  categoryId?: string;
  sortOrder?: number;
  salesVolume?: number;
  createdTime?: string;
  updatedTime?: string;
  status?: number;
  stock?: number;
  children?: SubCategoryItem[];
  description?: string;
}

interface ApiResponse {
  code: number;
  data: any;
  message?: string;
}

// 加载数据
const loadData = async () => {
  loading.value = true;
  try {
    const response = await getCostumeCategory();
    console.log("获取分类数据：", response);

    // 检查 response 和 response.data 是否存在且是数组
    if (response?.data && Array.isArray(response.data)) {
      categories.value = response.data.map(
        (category: CategoryWithChildren) => ({
          id: category.id || category.pid, // 兼容不同的 API 返回格式
          name: category.name,
          sort: parseInt(category.id || category.pid || "0"),
          showInBanner: category.categoryId === "1" || category.isBanner === 1,
          isRecommend:
            category.categoryId === "2" || category.isRecommend === 1 ? 1 : 0,
          // 一级分类使用url字段，始终添加前缀处理
          coverImage: category.url ? formatImageUrl(category.url) : "",
          description: category.description || category.descs || "",
          url: category.url || "", // 保留原始url字段
          children: Array.isArray(category.children)
            ? category.children.map(item => ({
                id: item.id,
                name: item.name,
                description: item.description || "",
                parentId: item.parentId,
                // 对于二级分类，使用icon作为图片字段，始终添加前缀处理
                coverImage: item.icon ? formatImageUrl(item.icon) : "",
                url: item.icon || "", // 二级分类使用icon字段
                previewImages: item.icon ? [formatImageUrl(item.icon)] : [],
                sort: item.sortOrder || 0,
                status: item.status || 0,
                price: item.price || 0,
                stock: item.stock || 0,
                createdTime: item.createdTime || "",
                updatedTime: item.updatedTime || "",
                updatedBy: item.updatedBy || null,
                salesVolume: item.salesVolume || 0
              }))
            : []
        })
      );

      // 默认展开第一个分类
      if (categories.value.length > 0) {
        activeCategories.value = [categories.value[0].id];
      }
    } else {
      // 如果 response.data 不是数组，设置为空数组
      categories.value = [];
      ElMessage.warning("没有获取到分类数据");
    }
  } catch (error) {
    console.error("加载分类数据失败:", error);
    ElMessage.error("加载分类数据失败");
    categories.value = []; // 确保在错误情况下也设置为空数组
  } finally {
    loading.value = false;
  }
};

// 表单数据
const categoryForm = reactive({
  name: "",
  sort: 0,
  parentId: undefined as string | undefined,
  previewImages: [] as string[],
  description: "",
  showInBanner: false,
  coverImage: "",
  isRecommend: 0,
  imageFile: null as File | null
});

// 表单验证规则
const rules = {
  name: [
    { required: true, message: "请输入分类名称", trigger: "blur" },
    { min: 2, max: 20, message: "长度在 2 到 20 个字符", trigger: "blur" }
  ],
  sort: [{ required: true, message: "请输入排序号", trigger: "blur" }]
};

// 重置表单
const resetForm = () => {
  categoryForm.name = "";
  categoryForm.sort = 0;
  categoryForm.parentId = undefined;
  categoryForm.previewImages = [];
  categoryForm.description = "";
  categoryForm.showInBanner = false;
  categoryForm.coverImage = "";
  categoryForm.isRecommend = 0;
  categoryForm.imageFile = null;
  if (formRef.value) {
    formRef.value.resetFields();
  }
};

// 处理添加分类
const handleAddCategory = () => {
  isSubCategory.value = false;
  parentCategory.value = null;
  currentCategory.value = null;
  categoryForm.sort = categories.value.length + 1;
  dialogVisible.value = true;
};

// 处理添加子分类
const handleAddSubCategory = (parent: any) => {
  isSubCategory.value = true;
  parentCategory.value = parent;
  currentCategory.value = null;
  categoryForm.parentId = parent.id;
  categoryForm.sort = (parent.children?.length || 0) + 1;
  dialogVisible.value = true;
};

// 处理编辑分类
const handleEditCategory = (row: any) => {
  isSubCategory.value = false;
  currentCategory.value = row;
  Object.assign(categoryForm, {
    name: row.name,
    sort: row.sort,
    showInBanner: row.showInBanner,
    coverImage: row.coverImage,
    description: row.description,
    isRecommend: row.isRecommend ? 1 : 0
  });
  dialogVisible.value = true;
};

// 处理编辑子分类
const handleEditSubCategory = (row: any) => {
  isSubCategory.value = true;
  currentCategory.value = row;
  const parent = categories.value.find(c => c.id === row.parentId);
  parentCategory.value = parent || null;
  Object.assign(categoryForm, {
    name: row.name,
    sort: row.sort,
    parentId: row.parentId,
    coverImage: row.coverImage,
    previewImages: row.previewImages || [],
    description: row.description
  });
  dialogVisible.value = true;
};

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return;

  await formRef.value.validate(async valid => {
    if (valid) {
      try {
        // 验证必填项 - 检查是否有图片
        if (!categoryForm.imageFile) {
          ElMessage.warning("请上传分类图片");
          return;
        }

        loading.value = true;
        ElMessage.info("正在处理请求，请稍候...");

        // 构建请求数据
        const formData = new FormData();
        formData.append("files", categoryForm.imageFile);

        // 确定参数
        const params: { name: string; descs: string; parentId?: string } = {
          name: categoryForm.name,
          descs: categoryForm.description || ""
        };

        // 如果是子分类，添加parentId参数
        if (isSubCategory.value && categoryForm.parentId) {
          params.parentId = categoryForm.parentId;
        }

        // 调用添加分类API
        const res = await addCategory(formData, params);

        // 根据后端实际响应结构处理
        if (res && res.data && res.code === 200 && res.data === true) {
          ElMessage.success("添加成功");
          dialogVisible.value = false;
          resetForm();
          loadData(); // 重新加载数据
        } else {
          const errorMsg = res?.data?.message || "添加分类失败";
          ElMessage.error(errorMsg);
        }
      } catch (error) {
        console.error("提交分类失败:", error);
        ElMessage.error("添加分类失败");
      } finally {
        loading.value = false;
        ElMessage.closeAll();
      }
    }
  });
};

// 预览图片
const handlePreviewImage = (url: string, allImages?: string[]) => {
  if (!url) return;

  if (allImages && allImages.length > 0) {
    // 如果提供了图片列表，使用该列表
    previewImages.value = allImages.filter(Boolean);
    // 找到当前图片在列表中的索引
    const index = previewImages.value.findIndex(img => img === url);
    previewIndex.value = index >= 0 ? index : 0;
  } else {
    // 否则只预览当前图片
    previewImages.value = [url];
    previewIndex.value = 0;
  }

  previewVisible.value = true;
};

// 处理上传成功
const handleUploadSuccess = (response: any) => {
  if (response.url) {
    if (categoryForm.previewImages.length < 9) {
      categoryForm.previewImages.push(formatImageUrl(response.url));
      ElMessage.success("上传成功");
    } else {
      ElMessage.warning("已达到上传上限");
    }
  }
};

// 处理封面上传成功
const handleCoverUploadSuccess = (
  uploadFile: UploadFile,
  uploadFiles: UploadFiles
) => {
  if (uploadFile.raw) {
    // 使用URL.createObjectURL创建本地预览URL
    categoryForm.coverImage = URL.createObjectURL(uploadFile.raw);
    // 保存文件对象以便后续上传
    categoryForm.imageFile = uploadFile.raw;
    ElMessage.success("图片选择成功");
  } else {
    ElMessage.error("图片选择失败");
  }
};

// 处理上传前的验证
const handleBeforeUpload = (file: File) => {
  const isImage = file.type.startsWith("image/");
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isImage) {
    ElMessage.error("只能上传图片文件!");
    return false;
  }
  if (!isLt2M) {
    ElMessage.error("图片大小不能超过 2MB!");
    return false;
  }

  return true;
};

// 处理对话框关闭
const handleDialogClose = () => {
  // 清理本地预览URL
  if (categoryForm.coverImage && categoryForm.coverImage.startsWith("blob:")) {
    URL.revokeObjectURL(categoryForm.coverImage);
  }
  resetForm();
};

// 处理删除分类
const handleDeleteCategory = (row: any) => {
  ElMessageBox.confirm("确定要删除该分类吗？删除后不可恢复！", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(async () => {
      // 调用删除API
      try {
        const res = await deleteCategory(row.id);

        if (
          res &&
          res.data &&
          res.data.code === 200 &&
          res.data.data === true
        ) {
          ElMessage.success("删除成功");
          loadData(); // 重新加载数据
        } else {
          ElMessage.error(res?.data?.message || "删除失败");
        }
      } catch (error) {
        console.error("删除分类失败:", error);
        ElMessage.error("删除失败");
      }
    })
    .catch(() => {});
};

// 加载子分类数据
const loadSubCategories = async (categoryId: string) => {
  if (!categoryId) return;

  loading.value = true;
  try {
    const response = await getSubCategories(categoryId);
    console.log("获取子分类数据：", response);

    if (response?.data && Array.isArray(response.data)) {
      // 找到当前分类
      const category = categories.value.find(c => c.id === categoryId);
      if (category) {
        // 只显示二级分类，三级分类通过二级分类的children属性存储
        const secondLevelCategories = [];

        // 处理每个二级分类
        for (const item of response.data) {
          // 添加二级分类
          const secondLevelItem = {
            id: item.id,
            name: item.name,
            description: item.description || "",
            parentId: categoryId,
            // 使用icon作为二级分类的图片，始终添加前缀处理
            coverImage: item.icon ? formatImageUrl(item.icon) : "",
            url: item.icon || "", // 保留原始url字段
            previewImages: [],
            sort: item.sortOrder || 0,
            status: item.status || 0,
            stock: item.stock || 0,
            createdTime: item.createdTime || "",
            updatedTime: item.updatedTime || "",
            isSecondLevel: true, // 标记为二级分类
            childCount: item.children?.length || 0,
            children: [] // 存储子分类
          };

          // 添加该二级分类下的所有三级分类
          if (Array.isArray(item.children) && item.children.length > 0) {
            secondLevelItem.children = item.children.map(child => ({
              id: child.id,
              name: child.name,
              description: child.description || "",
              parentId: item.id,
              parentName: item.name, // 保存父分类名称
              coverImage: child.url ? formatImageUrl(child.url) : "",
              url: child.url || "", // 保留原始url字段
              previewImages: child.url ? [formatImageUrl(child.url)] : [],
              sort: child.sortOrder || 0,
              status: child.status || 0,
              price: child.price || 0,
              stock: child.stock || 0,
              createdTime: child.createdTime || "",
              updatedTime: child.updatedTime || "",
              updatedBy: child.updatedBy || null,
              salesVolume: child.salesVolume || 0,
              isThirdLevel: true // 标记为三级分类
            }));
          }

          secondLevelCategories.push(secondLevelItem);
        }

        // 更新分类的子分类，只包含二级分类
        category.children = secondLevelCategories;

        console.log("category.children", category.children);
      }
    } else {
      // 如果没有子分类数据，设置为空数组
      const category = categories.value.find(c => c.id === categoryId);
      if (category) {
        category.children = [];
      }
    }
  } catch (error) {
    console.error("加载子分类数据失败:", error);
    ElMessage.error("加载子分类数据失败");
  } finally {
    loading.value = false;
  }
};

// 在展开分类时加载子分类
const handleCategoryExpand = (expandedIds: string[]) => {
  if (expandedIds && expandedIds.length > 0) {
    // 找出新展开的分类ID
    const newExpandedIds = expandedIds.filter(
      id => !activeCategories.value.includes(id)
    );

    // 为每个新展开的分类加载子分类
    newExpandedIds.forEach(categoryId => {
      loadSubCategories(categoryId);
    });
  }
};

// 修改 activeCategories 的 watch
watch(activeCategories, newVal => {
  if (newVal.length > 0) {
    // 当展开分类时，加载该分类的子分类数据
    newVal.forEach(categoryId => {
      if (!categories.value.find(c => c.id === categoryId)?.children?.length) {
        loadSubCategories(categoryId);
      }
    });
  }
});

// 处理删除子分类
const handleDeleteSubCategory = (row: any) => {
  ElMessageBox.confirm("确定要删除该子分类吗？删除后不可恢复！", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(async () => {
      try {
        // 调用删除子分类API
        const res = await deleteCategory(row.id); // 假设使用相同的删除API

        if (
          res &&
          res.data &&
          res.data.code === 200 &&
          res.data.data === true
        ) {
          ElMessage.success("删除成功");
          // 如果有父分类ID，只重新加载该父分类的子分类
          if (row.parentId) {
            loadSubCategories(row.parentId);
          } else {
            loadData(); // 重新加载所有数据
          }
        } else {
          ElMessage.error(res?.data?.message || "删除失败");
        }
      } catch (error) {
        console.error("删除子分类失败:", error);
        ElMessage.error("删除失败");
      }
    })
    .catch(() => {});
};

// 处理轮播展示切换
const handleBannerToggle = async (value: boolean) => {
  if (!currentCategory.value) return;

  try {
    const res = await updateCostumeCategory({
      pid: currentCategory.value.id,
      isBanner: value ? 1 : 0
    });

    if (res && res.data && res.data.code === 200 && res.data.data === true) {
      ElMessage.success(`${value ? "已设置" : "已取消"}轮播展示`);
      loadData(); // 重新加载数据
    } else {
      ElMessage.error(res?.data?.message || "更新轮播状态失败");
      // 恢复原状态
      categoryForm.showInBanner = !value;
    }
  } catch (error) {
    console.error("更新轮播状态失败:", error);
    ElMessage.error("更新轮播状态失败");
    // 恢复原状态
    categoryForm.showInBanner = !value;
  }
};

// 处理推荐分类切换
const handleRecommendToggle = async (value: number) => {
  if (!currentCategory.value) return;

  try {
    const res = await updateCostumeCategory({
      pid: currentCategory.value.id,
      isRecommend: value
    });

    if (res && res.data && res.data.code === 200 && res.data.data === true) {
      ElMessage.success(`${value === 1 ? "已设置" : "已取消"}推荐分类`);
      loadData(); // 重新加载数据
    } else {
      ElMessage.error(res?.data?.message || "更新推荐状态失败");
      // 恢复原状态
      categoryForm.isRecommend = value === 1 ? 0 : 1;
    }
  } catch (error) {
    console.error("更新推荐状态失败:", error);
    ElMessage.error("更新推荐状态失败");
    // 恢复原状态
    categoryForm.isRecommend = value === 1 ? 0 : 1;
  }
};

// 计算对话框标题
const getDialogTitle = computed(() => {
  if (currentCategory.value) {
    return isSubCategory.value ? "编辑子分类" : "编辑分类";
  }
  return isSubCategory.value ? "新增子分类" : "新增分类";
});

// 处理查看子分类
const handleViewSubCategories = (row: any) => {
  if (row.isSecondLevel && row.children && row.children.length > 0) {
    currentSubCategory.value = row;
    subCategoryDialogVisible.value = true;
  } else {
    ElMessage.info("该分类没有子分类");
  }
};

// 处理添加三级分类
const handleAddThirdCategory = (row: any) => {
  isSubCategory.value = true;
  parentCategory.value = row;
  currentCategory.value = null;

  // 重置表单
  resetForm();

  // 设置父分类ID
  categoryForm.parentId = row.id;

  // 打开对话框
  dialogVisible.value = true;
};

// 获取行的类名
const getRowClassName = ({ row }: { row: any }) => {
  if (row.isSecondLevel) {
    return "second-level-row";
  } else if (row.isThirdLevel) {
    return "third-level-row";
  }
  return "";
};

// 初始化
onMounted(() => {
  loadData();
});

// 添加数据对象
const selectedCategoryForm = reactive({
  parentId: "",
  secondId: "",
  name: "",
  imageUrl: ""
});
</script>

<style lang="scss" scoped>
@use "@/styles/mixins.scss" as *;

.costume-container {
  padding: 24px;
  background: var(--el-bg-color-page);

  .category-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 24px;
      padding: 8px 0;
      border-bottom: 1px solid var(--el-border-color-light);

      .left {
        display: flex;
        align-items: center;
        gap: 12px;

        .title {
          font-size: 18px;
          font-weight: 600;
          color: var(--el-text-color-primary);
        }
      }
    }

    .category-list {
      :deep(.el-collapse) {
        --el-collapse-border-color: transparent;

        .el-collapse-item {
          margin-bottom: 20px;
          border: 1px solid var(--el-border-color-light);
          border-radius: 8px;
          overflow: hidden;
          transition: all 0.3s;
          background: #fff;
          box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);

          &:hover {
            box-shadow: var(--el-box-shadow-light);
          }

          .el-collapse-item__header {
            background: var(--el-fill-color-light);
            border-bottom: 1px solid var(--el-border-color-lighter);
            padding: 0 20px;
            height: auto;
            line-height: normal;
          }

          .el-collapse-item__content {
            padding: 20px;
          }
        }
      }

      .category-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 16px 0;
        width: 100%;

        .category-info {
          display: flex;
          align-items: center;
          gap: 8px;
          flex-wrap: wrap;

          .name {
            font-size: 16px;
            font-weight: 600;
            color: var(--el-text-color-primary);
          }
        }
      }

      .category-cover {
        border: 1px solid #ebeef5;
        box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
        transition: all 0.3s;
        cursor: pointer;
      }

      .category-cover:hover {
        transform: scale(1.05);
      }

      .sub-categories {
        .name-cell {
          display: flex;
          align-items: center;
          gap: 8px;
          flex-wrap: wrap;

          .parent-name {
            color: var(--el-text-color-secondary);
            font-size: 13px;
          }

          .second-level {
            font-weight: 600;
            color: var(--el-color-primary);
          }

          .sub-category-name {
            font-weight: 500;
            color: var(--el-text-color-primary);
          }
        }

        .favorite-tag {
          display: flex;
          align-items: center;
          gap: 4px;
          padding: 4px 8px;

          .el-icon {
            margin-right: 2px;
          }
        }

        .preview-images {
          padding: 12px;
          display: flex;
          overflow: auto;

          .images-wrapper {
            display: flex;
            gap: 12px;
            align-items: center;
            flex-wrap: nowrap;
          }

          .preview-image {
            width: 80px;
            height: 80px;
            border-radius: 6px;
            object-fit: contain;
            cursor: pointer;
            transition: transform 0.3s;
            border: 1px solid var(--el-border-color-lighter);
            background-color: #f5f7fa;

            &:hover {
              transform: scale(1.05);
            }
          }

          .image-slot {
            display: flex;
            justify-content: center;
            align-items: center;
            width: 100%;
            height: 100%;
            background: var(--el-fill-color-light);
            color: var(--el-text-color-secondary);
            font-size: 20px;
          }
        }

        :deep(.el-table) {
          --el-table-border-color: var(--el-border-color-lighter);
          --el-table-header-bg-color: var(--el-fill-color-light);
          --el-table-row-hover-bg-color: var(--el-fill-color);
          border-radius: 8px;
          overflow: hidden;
          box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.03);

          th {
            font-weight: 600;
          }

          td {
            padding: 12px;
          }

          .el-table__row.second-level-row {
            background-color: rgba(var(--el-color-primary-rgb), 0.05);
          }

          .el-table__row.third-level-row {
            background-color: rgba(var(--el-color-success-rgb), 0.05);
          }
        }
      }
    }
  }
}

.costume-uploader {
  .preview-image {
    width: 200px;
    height: 200px;
    object-fit: cover;
  }

  .uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 200px;
    height: 200px;
    text-align: center;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    display: flex;
    align-items: center;
    justify-content: center;

    &:hover {
      border-color: var(--el-color-primary);
    }
  }

  .upload-tip {
    font-size: 12px;
    color: #999;
    margin-top: 8px;
  }
}

.detail-uploader {
  :deep(.el-upload--picture-card) {
    width: 150px;
    height: 150px;
    line-height: 150px;
  }
}

.preview-images {
  display: flex;
  gap: 8px;
  align-items: center;
  margin-bottom: 8px;
  flex-wrap: wrap;

  .preview-image {
    width: 100px;
    height: 100px;
    border-radius: 4px;
    object-fit: contain;
  }

  .upload-preview {
    width: 100px;
    height: 100px;
    border: 1px dashed var(--el-border-color);
    border-radius: 4px;
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;
    color: var(--el-text-color-secondary);

    &:hover {
      border-color: var(--el-color-primary);
      color: var(--el-color-primary);
    }
  }
}

.upload-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
  display: flex;
  justify-content: space-between;
  align-items: center;

  .warning {
    color: var(--el-color-warning);
  }
}

.cover-upload {
  width: 200px;
  height: 200px;
  margin-bottom: 8px;

  .cover-preview {
    width: 100%;
    height: 100%;
    border-radius: 8px;
    border: 1px solid var(--el-border-color-lighter);
  }

  .upload-cover {
    width: 100%;
    height: 100%;

    :deep(.el-upload) {
      width: 100%;
      height: 100%;
    }
  }

  .upload-placeholder {
    width: 100%;
    height: 100%;
    border: 1px dashed var(--el-border-color);
    border-radius: 8px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    cursor: pointer;
    transition: all 0.3s;

    .el-icon {
      font-size: 24px;
      color: var(--el-text-color-secondary);
      margin-bottom: 8px;
    }

    span {
      color: var(--el-text-color-secondary);
      font-size: 14px;
    }

    &:hover {
      border-color: var(--el-color-primary);

      .el-icon,
      span {
        color: var(--el-color-primary);
      }
    }
  }
}

.form-tip {
  font-size: 12px;
  color: var(--el-text-color-secondary);
  margin-top: 4px;
}

.cover-thumbnail {
  width: 60px;
  height: 60px;
  border-radius: 4px;
  cursor: pointer;
  transition: transform 0.3s;
  border: 1px solid var(--el-border-color-lighter);
  object-fit: cover;

  &:hover {
    transform: scale(1.05);
  }
}

.no-cover {
  width: 60px;
  height: 60px;
  border-radius: 4px;
  border: 1px dashed var(--el-border-color);
  display: flex;
  justify-content: center;
  align-items: center;
  color: var(--el-text-color-secondary);
}

.second-level-header {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 4px 0;

  .sub-category-name {
    font-weight: 600;
    color: var(--el-color-primary);
    font-size: 15px;
  }
}

.sub-category-dialog {
  :deep(.el-dialog__header) {
    border-bottom: 1px solid var(--el-border-color-light);
    margin-right: 0;
    padding-bottom: 15px;
  }

  .dialog-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    .info {
      display: flex;
      align-items: center;
      gap: 12px;

      .category-name {
        font-size: 16px;
        font-weight: 600;
        color: var(--el-text-color-primary);
      }
    }
  }
}

/* AI上传对话框样式 */
:deep(.ai-upload-dialog) {
  .el-dialog__header {
    padding: 20px 24px;
    margin-right: 0;
    border-bottom: 1px solid #ebeef5;
  }

  .el-dialog__body {
    padding: 24px;
    max-height: 570px; /* 对话框高度减去头部和底部的高度 */
    overflow-y: auto;
  }

  .el-dialog {
    --el-dialog-width: 800px;
    height: 640px;
    overflow: hidden;
  }
}

.ai-upload-container {
  // display: flex;
  // flex-wrap: wrap;
  // gap: 24px;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-evenly;
  align-items: stretch;
  gap: 50px;
  align-content: space-around;
  flex-direction: column-reverse;

  @media (max-width: 768px) {
    flex-direction: column;
  }
}

.preview-area {
  width: 400px;
  height: 400px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;

  .preview-card {
    width: 100%;
    height: 100%;
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    overflow: hidden;
    padding: 16px;
    display: flex;
    flex-direction: column;
  }

  .ai-upload {
    width: 100%;
    height: 100%;
    position: relative;
    overflow: hidden;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: #fafafa;
    border-radius: 6px;

    .upload-placeholder {
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      width: 100%;
      height: 100%;
      padding: 65px;
      border: 2px dashed #409eff;
      border-radius: 6px;
      cursor: pointer;
      background-color: #f0f7ff;
      transition: all 0.3s;

      &:hover {
        background-color: #ecf5ff;
        border-color: #66b1ff;
        transform: scale(1.01);
      }

      .el-icon {
        font-size: 48px;
        color: #409eff;
        margin-bottom: 16px;
      }

      span {
        color: #409eff;
        font-size: 18px;
        font-weight: 500;
      }

      .upload-tip {
        margin-top: 12px;
        font-size: 12px;
        color: #909399;
      }
    }

    .preview-image {
      max-width: 100%;
      max-height: 100%;
      width: auto;
      height: auto;
      object-fit: contain;
      border-radius: 6px;
      transition: all 0.3s;
      margin: auto;
      display: block;
      position: absolute;
      top: 0;
      bottom: 0;
      left: 0;
      right: 0;
    }

    .image-overlay {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      background-color: rgba(0, 0, 0, 0.6);
      opacity: 0;
      transition: opacity 0.3s;
      cursor: pointer;
      border-radius: 6px;

      .el-icon {
        font-size: 34px;
        color: #fff;
        margin-bottom: 16px;
      }

      span {
        color: #fff;
        font-size: 16px;
        font-weight: 500;
      }
    }

    &:hover {
      .image-overlay {
        opacity: 1;
      }

      .preview-image {
        filter: blur(1px);
      }
    }
  }

  .action-row {
    margin-top: 16px;
    display: flex;
    justify-content: center;

    .analyze-btn {
      width: 100%;
      background: linear-gradient(90deg, #409eff, #67c23a);
      border: none;
      transition: all 0.3s;

      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
      }
    }
  }
}

.prediction-area {
  flex: 1;
  min-width: 300px;
  background-color: #fff;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;

  &:hover {
    box-shadow: 0 8px 20px rgba(0, 0, 0, 0.15);
  }

  .prediction-header {
    display: flex;
    align-items: center;
    gap: 12px;
    margin-bottom: 24px;
    position: relative;

    &:after {
      content: "";
      position: absolute;
      bottom: -12px;
      left: 0;
      width: 100%;
      height: 1px;
      background: linear-gradient(
        90deg,
        rgba(64, 158, 255, 0.1),
        rgba(103, 194, 58, 0.1)
      );
    }

    .header-icon {
      display: flex;
      justify-content: center;
      align-items: center;
      width: 40px;
      height: 40px;
      border-radius: 50%;
      background: linear-gradient(135deg, #409eff, #67c23a);
      box-shadow: 0 4px 8px rgba(64, 158, 255, 0.3);

      .el-icon {
        color: #fff;
        font-size: 22px;
      }
    }

    h3 {
      margin: 0;
      font-size: 20px;
      color: #303133;
      font-weight: 600;
      background: linear-gradient(90deg, #409eff, #67c23a);
      -webkit-background-clip: text;
      color: transparent;
    }
  }

  .prediction-list {
    display: flex;
    flex-direction: column;
    gap: 12px;
    width: 100%;
    margin-top: 20px;
  }

  .prediction-item {
    padding: 14px;
    background-color: #f9f9f9;
    border-radius: 10px;
    transition: all 0.3s;
    border: 1px solid transparent;
    position: relative;
    overflow: hidden;

    &:hover {
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
      background-color: #f5f7fa;
      transform: translateY(-2px);
    }

    &.is-selected {
      border-color: #67c23a;
      background-color: #f0f9eb;

      &:before {
        content: "";
        position: absolute;
        top: 0;
        left: 0;
        width: 5px;
        height: 100%;
        background: linear-gradient(to bottom, #67c23a, #409eff);
      }
    }

    &.high-confidence {
      background-color: rgba(103, 194, 58, 0.1);

      &.is-selected {
        background-color: rgba(103, 194, 58, 0.2);
        border-color: #67c23a;
      }
    }

    .el-radio {
      width: 100%;
      margin-right: 0;

      :deep(.el-radio__label) {
        width: 100%;
        padding-left: 8px;
      }
    }
  }

  .prediction-content {
    display: flex;
    flex-direction: column;
    width: 100%;
  }

  .prediction-info {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
  }

  .prediction-name {
    font-size: 16px;
    font-weight: 600;
    color: #303133;
    display: flex;
    align-items: center;
    gap: 6px;
  }

  .prediction-percent {
    font-size: 15px;
    color: #409eff;
    font-weight: 500;
    padding: 2px 8px;
    border-radius: 12px;
    background-color: rgba(64, 158, 255, 0.1);

    &.high-percent {
      color: #67c23a;
      background-color: rgba(103, 194, 58, 0.1);
      font-weight: 600;
    }
  }

  .prediction-bar {
    width: 100%;
    height: 8px;
    background-color: #e4e7ed;
    border-radius: 4px;
    overflow: hidden;
    position: relative;

    &:after {
      content: "";
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.1));
    }
  }

  .prediction-progress {
    height: 100%;
    background: linear-gradient(90deg, #409eff, #67c23a);
    border-radius: 4px;
    transition: width 0.8s cubic-bezier(0.25, 1, 0.5, 1);
    position: relative;
    overflow: hidden;

    &:after {
      content: "";
      position: absolute;
      top: 0;
      left: 0;
      width: 30px;
      height: 100%;
      background: rgba(255, 255, 255, 0.2);
      animation: shine 1.5s infinite;
    }
  }

  .action-row {
    display: flex;
    justify-content: center;
    margin-top: 30px;

    .add-category-btn {
      min-width: 180px;
      background: linear-gradient(90deg, #67c23a, #409eff);
      border: none;
      transition: all 0.3s;
      padding: 12px 28px;
      font-size: 16px;
      border-radius: 8px;

      &:hover {
        transform: translateY(-3px);
        box-shadow: 0 6px 16px rgba(103, 194, 58, 0.3);
      }

      &:active {
        transform: translateY(-1px);
      }

      &:disabled {
        opacity: 0.7;
        background: linear-gradient(90deg, #909399, #c0c4cc);
      }
    }
  }
}

.manual-item {
  margin-top: 20px;
  border-top: 1px dashed #e4e7ed;
  padding-top: 16px;

  .manual-icon {
    color: #409eff;
    font-size: 18px;
    margin-right: 4px;
  }
}

.manual-input-area {
  margin-top: 16px;
  margin-bottom: 20px;
  padding: 0 14px;

  :deep(.el-input) {
    --el-input-border-radius: 8px;
    --el-input-height: 44px;

    .el-input__wrapper {
      box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
      transition: all 0.3s;

      &:hover {
        box-shadow: 0 2px 8px rgba(64, 158, 255, 0.2);
      }

      &.is-focus {
        box-shadow: 0 2px 10px rgba(64, 158, 255, 0.3);
      }
    }

    .el-input__prefix {
      color: #409eff;
    }
  }
}

@keyframes shine {
  0% {
    transform: translateX(-100%);
  }
  100% {
    transform: translateX(500%);
  }
}

/* 图片查看器样式优化 */
:deep(.el-image-viewer__wrapper) {
  .el-image-viewer__img {
    max-width: 100%;
    max-height: 100%;
    display: block;
    margin: 0 auto;
  }
}

/* 分类选择对话框样式 */
.category-selection-dialog {
  :deep(.el-dialog__header) {
    padding: 20px 24px;
    margin-right: 0;
    border-bottom: 1px solid #f0f0f0;

    .el-dialog__title {
      font-size: 18px;
      font-weight: 600;
      color: #303133;
    }
  }

  .dialog-content {
    padding: 20px 0;

    .el-form {
      width: 100%;
      max-width: 600px;
      margin: 0 auto;

      .el-form-item {
        margin-bottom: 24px;
      }

      .el-select {
        width: 100%;
      }
    }
  }

  .el-select-dropdown__item {
    &.selected {
      color: #67c23a;
      font-weight: 600;
    }
  }

  :deep(.el-dialog__footer) {
    border-top: 1px solid #f0f0f0;
    padding: 16px 24px;

    .el-button {
      min-width: 120px;
      background: linear-gradient(90deg, #67c23a, #409eff);
      color: white;
      border: none;

      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(103, 194, 58, 0.3);
      }

      &:disabled {
        opacity: 0.7;
        background: linear-gradient(90deg, #909399, #c0c4cc);
      }
    }
  }
}
</style>
